/**
 * 图片上传类
 */
import { HTTP_REQUEST_URL,TOKEN_ID } from '../config.js'

export default class UploadImg {
	/**
	 * [constructor description]
	 * @param  {[Array]} files [chooseImg选中的tempFilePaths]
	 * @param  {[Object]} json  [success每上传成功一张调用 complete全部上传完成调用]
	 * @return {[void]}       [description]
	 */
	constructor(files, json) {
		if (!Array.isArray(files)) {
			throw new Error('Class UploadImg parameter must be an array');
		}
		this.data = [];
		this.fn = json.success;
		this.complete = json.complete;
		this.files = files;
		this.fileLen = this.files.length;
		this.curIndex = 0;
		// this.datas='';
		uni.showLoading({
			title: '上传中',
			mask:true
		});
		this.upload();
	}

	upload() {
		let _this = this;
		console.log(this.files[this.curIndex])
		let images = [this.files[this.curIndex]]
		uni.uploadFile({
			url: HTTP_REQUEST_URL+'/5d5fa8984f0c2', 
			filePath: this.files[this.curIndex],
			// filePath:images,
			name: 'file',
			header: {
				'user-token': uni.getStorageSync(TOKEN_ID),
			},
			success: res => {
				console.log(res)
				console.log(res.data)
				let data = JSON.parse(res.data);
				console.log(data);
				if (data.code == 1) {
					let dataList = data.data;
					console.log(dataList)
					this.data.push({
						img_url:dataList[0]
					});
					if (this.fn) this.fn(this.data);
				} else {
					uni.showToast({
						title: "图片上传失败，请重试",
						position: "center",
						icon: 'none',
						duration: 2500
					})
					uni.hideLoading()
				}
			},
			complete: () => {
				this.curIndex++; //这个图片执行完上传后，开始上传下一张
				if (this.curIndex == this.fileLen) { //当图片传完时，停止调用
					this.complete(this.data);
					// this.complete(this.datas)
					uni.showToast({
						title: "图片上传成功",
						position: "center",
						icon: 'none',
						duration: 2500
					})
					// uni.hideLoading()
				} else { //若图片还没有传完，则继续调用函数
					this.upload();
				}
			}
		});
	}
}



// //单图上传图片
// const chooseImage = (tps) => {
//   console.log(this.Litestore.card_image)
//   let _this = this;
//   uni.chooseImage({
//     count: 6, //默认9
//     sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
//     sourceType: ['album'], //从相册选择
//     success: function(res) {
//       const tempFilePaths = res.tempFilePaths;

//     }
//   });
// }
